<?php

class ForgotPassword extends TPage
{
	public function onLoad($param)
	{
		parent::onLoad($param);
		if (!$this->Application->User->IsGuest)
			$this->Response->redirect($this->Service->ConstructUrl("Index"));

		if (!$this->IsPostBack)
		{
			$this->Master->pageHead->Title = $this->Application->Parameters["WEBSITE_TITLE"]." - Forgot Password";
			$this->Master->cssMenuLogIn->Value = "current_menu_item";
		}
	}
	
	public function btnForgotPassword_Clicked($sender, $param)
	{
		
		if ($this->IsValid)
		{
			$user = UserRecord::finder()->findByuser_email($this->txtLoginEmail->SafeText);
			if ($user instanceof UserRecord)
			{
				// do reset password
				$new_pass = uniqid();
				$user->Password = md5($new_pass);
				$user->ModifyDate = time();
				$user->ModifyBy = $user->ID;
				$user->save();				
				
				$emailer = $this->Application->getModule('mailer');
				$email = $emailer->createNewEmail("ForgotPassword");
				$email->HtmlContent->findControl("USER_NAME")->Text = $user->UserName;
				$email->HtmlContent->findControl("NEW_PASSWORD")->Text = $new_pass;
	
				$loginUrl = $this->Request->BaseUrl;
				if(stristr($this->Request->BaseUrl, 'localhost'))
					$loginUrl = $loginUrl . "/latenightdine";
	
				$email->HtmlContent->findControl("lnkLogin")->NavigateUrl = $loginUrl."/login.html";
				$receiver = new TEmailAddress;
				$receiver->Field = TEmailAddressField::Receiver;
				$receiver->Address = $user->Email;
				$receiver->Name = $user->UserName;
				$email->getEmailAddresses()->add($receiver);
						
				try
				{
					$emailer->send($email);
					$this->noticeMsg->Text = $this->Application->getModule('message')->translate("NEW_PASSWORD_SENT");
					$this->noticeMsg->Visible = true;
					$this->noticePanel->Visible = true;
					$this->resetPwdPanel->Visible = false;
				}
				catch(TException $e)
				{
					$this->noticeMsg->Text = $this->Application->getModule('message')->translate("UNKNOWN_ERROR");
					$this->noticeMsg->Visible = true;
					$this->noticePanel->Visible = true;
					$this->resetPwdPanel->Visible = false;
				}
			}
			else
			{
				$this->Notice->Type = UserNoticeType::Error;
				$this->Notice->Text = $this->Application->getModule('message')->translate("ITEM_NOT_FOUND", "Email");
			}
		}
	}
}

?>